package utils;

import java.text.MessageFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;

/**
 *Description:
 * 1、替换${key}的字符串为 Map对应的值即Map.get(key)
 *
 *Version:1.0.0
 *@author shihb
 *@date 2020/11/11 23:17
 */
public class ParseUtil {

  public static String  parseExprStr(String templateStr, Map<String, Object> data) {
    return parseExprStr(templateStr,data,"0");
  }
  /**
   * 把字符串的变量替换成Map中对应key的值
   * 如果没有匹配到,或者Map的value是空串就替换成指定默认值,
   * 默认值不指定默认为"0"
   * 报错或者templateStr为空null返回null
   * @param templateStr 要替换的字符串
   * @param data 要替换的map
   * @param nullReplaceVal 空值替换的默认值
   * @return
   */
  public static String  parseExprStr(String templateStr, Map<String, Object> data, String nullReplaceVal) {

    if(StringUtils.isBlank(templateStr)) return null;

    try {
      if(data == null) data = Collections.EMPTY_MAP;
      nullReplaceVal = nullReplaceVal==null ? "0" : nullReplaceVal;
//      Pattern pattern = Pattern.compile("\\$\\{([^}]+)}");
      Pattern pattern = Pattern.compile("\\$\\{([^}]+)}");
      StringBuffer newValue = new StringBuffer(templateStr.length());
      Matcher matcher = pattern.matcher(templateStr);
      while (matcher.find()) {
        String key = matcher.group(1);
        Object val = data.get(key);
        String valStr =data.get(key)!=null? StringUtils.trimToNull(val.toString()):null;
        String r= valStr!=null?valStr:nullReplaceVal;
        matcher.appendReplacement(newValue, r.replaceAll("\\\\", "\\\\\\\\")); //这个是为了替换windows下的文件目录在java里用\\表示
      }
      matcher.appendTail(newValue);
      return newValue.toString();
    } catch (Exception e) {
      return null;
    }


  }

  /**
   * 解析占位符,报错返回null
   * @param exprStr 占位符表达式{index} index的下标变对应 数组的值
   * @param objects 占位符对应的数组
   * @param prefix  给数组的值加前缀
   * @param suffix 给数组的值加后缀
   * @return
   */
  public static String parsePlaceholder(String exprStr,Object[] objects,String prefix,String suffix){
    if(suffix==null && prefix==null){
    }else{
      suffix = StringUtils.trimToEmpty(suffix);
      prefix = StringUtils.trimToEmpty(prefix);
      for(int i=0;i<objects.length;i++){
        objects[i]=prefix+objects[i]+suffix;
      }
    }

    try {
      MessageFormat messageFormat = new MessageFormat(exprStr);
      return messageFormat.format(objects);
    } catch (Exception e) {
      return null;
    }

  }

  public static String parsePlaceholder(String exprStr,Object[] objects){
    return  parsePlaceholder(exprStr,objects,null,null);
  }






}

